//
//  SMPopupWindowContainer.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/11.
//

import SwiftUI

// 专门用于 Window 的弹窗容器（完全独立）
struct SMPopupWindowContainer<Content: View>: View {
    let config: SMPopupConfig
    let content: Content
    let onDismiss: () -> Void
    let onDismissHandlerAvailable: ((@escaping () -> Void) -> Void)?
    
    @State private var isPresented = false
    
    init(
        config: SMPopupConfig,
        @ViewBuilder content: () -> Content,
        onDismiss: @escaping () -> Void,
        onDismissHandlerAvailable: ((@escaping () -> Void) -> Void)? = nil
    ) {
        self.config = config
        self.content = content()
        self.onDismiss = onDismiss
        self.onDismissHandlerAvailable = onDismissHandlerAvailable
    }
    
    var body: some View {
        ZStack(alignment: config.style == .actionSheet ? .bottom : .center) {
            if isPresented {
                // 遮罩层 - 每个弹窗都有自己的遮罩
                config.overlayColor
                    .ignoresSafeArea()
                    .onTapGesture {
                        if config.dismissOnTapOutside {
                            dismissWithAnimation()
                        }
                    }
                    .transition(.opacity)
                
                // 弹窗内容
                popupContent
                    .transition(transitionForStyle)
            }
        }
        .animation(config.animation, value: isPresented)
        .onAppear {
            print("弹窗容器出现")
            withAnimation(config.animation) {
                isPresented = true
            }
            
            // 将 dismiss 方法传递给外部
            onDismissHandlerAvailable? {
                dismissWithAnimation()
            }
        }
        .background(Color.clear)
        .ignoresSafeArea()
    }
    
    private func dismissWithAnimation() {
        print("弹窗容器开始关闭动画")
        withAnimation(config.animation) {
            isPresented = false
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            print("弹窗容器执行 onDismiss")
            self.onDismiss()
        }
    }
    
    private var transitionForStyle: AnyTransition {
        switch config.style {
        case .alert:
            return .asymmetric(
                insertion: .scale(scale: 0.5, anchor: .center).combined(with: .opacity),
                removal: .scale(scale: 0.8, anchor: .center).combined(with: .opacity)
            )
        case .actionSheet:
            return .asymmetric(
                insertion: .move(edge: .bottom).combined(with: .opacity),
                removal: .move(edge: .bottom).combined(with: .opacity)
            )
        }
    }
    
    private var popupContent: some View {
        Group {
            switch config.style {
            case .alert:
                alertContent
            case .actionSheet:
                actionSheetContent
            }
        }
    }
    
    private var alertContent: some View {
        content
            .frame(maxWidth: .infinity)
            .background(backgroundView)
            .cornerRadius(config.cornerRadius)
            .shadow(color: config.shadowColor, radius: config.shadowRadius)
            .padding(config.padding)
    }
    
    private var actionSheetContent: some View {
        VStack {
            content
                .frame(maxWidth: .infinity)
                .background(backgroundView)
                .cornerRadius(config.cornerRadius)
                .shadow(color: config.shadowColor, radius: config.shadowRadius)
                .padding(.horizontal, config.padding)
        }
    }
    
    @ViewBuilder
    private var backgroundView: some View {
        if let backgroundImage = config.backgroundImage {
            Image(backgroundImage)
                .resizable()
                .aspectRatio(contentMode: config.backgroundImageContentMode)
                .opacity(config.backgroundImageOpacity)
                .cornerRadius(config.cornerRadius)
        } else {
            config.backgroundColor
                .cornerRadius(config.cornerRadius)
        }
    }
}

